package weaver.interfaces.shengxu.duss.utils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import okhttp3.*;
import weaver.common.DateUtil;
import weaver.conn.RecordSet;
import weaver.formmode.setup.ModeRightInfo;
import weaver.general.BaseBean;
import weaver.general.TimeUtil;
import weaver.general.Util;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author dusongsong
 * @date 2024年06月03日 17:13
 */
public class U9Util extends BaseBean {


    private static final MediaType mediaType = MediaType.parse("application/json; charset=utf-8");
    private static final int CONNECT_TIMEOUT_MILLIS = 60 * 1000; // 60秒
    private static final int READ_TIMEOUT_MILLIS = 60 * 1000; // 60秒
    private static final int WRITE_TIMEOUT_MILLIS = 60 * 1000; // 60秒
    private OkHttpClient client;
    // 定义常量
    private static final String CODE_SUCCESS = "success";
    private static final String CODE_FAIL = "fail";
    private static final String MESSAGE_SUCCESS = "success";
    private static final String MESSAGE_FAIL = "fail";
    private static final String RES_CODE_ZERO = "0";
    private static final String IS_SUCCESS_TRUE = "true";

    public U9Util() {
        this.client = new OkHttpClient.Builder()
                .connectTimeout(CONNECT_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS)
                .readTimeout(READ_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS)
                .writeTimeout(WRITE_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS)
                .build();
    }

    /**
     * 客户创建
     *
     * @param paramsList
     * @return
     */
    public JSONObject CreateCustomer(JSONArray paramsList, String requestid, String src) {
        JSONObject returnJson = new JSONObject();
        // 默认设置为失败
        returnJson.put("code", CODE_FAIL);
        returnJson.put("message", MESSAGE_FAIL);
        Map<String, Object> apilogMap = new HashMap<>();
        apilogMap.put("jkdymc", "WeaKhszrsqlcAction");
        apilogMap.put("lcid", requestid);
        apilogMap.put("cz", src);
        String baseUrl = Util.null2String(getPropValue("u9", "url"));
        String apiUrl = "/U9C/webapi/CustCustomer/CreateCustomer";
        JSONObject resultJson = doApiLog(paramsList, apilogMap, baseUrl + apiUrl);
        writeLog(">>>>>CreateCustomer>>>>>resultJson=" + resultJson);
        if (MESSAGE_SUCCESS.equals(resultJson.getString("message"))) {
            JSONObject dataJson = resultJson.getJSONObject("data");
            if (RES_CODE_ZERO.equals(dataJson.getString("ResCode"))) {
                JSONArray resultData = dataJson.getJSONArray("Data");
                if (!resultData.isEmpty()) {
                    JSONObject firstObject = resultData.getJSONObject(0);
                    String isSucess = firstObject.getString("IsSucess");
                    if (IS_SUCCESS_TRUE.equals(isSucess)) {
                        returnJson.put("code", CODE_SUCCESS);
                        String data = firstObject.getString("ID");
                        returnJson.put("data", data);
                    } else {
                        returnJson.put("message", firstObject.getString("ErrorMsg"));
                    }
                } else {
                    returnJson.put("message", Util.null2String(dataJson.getString("ResMsg")));
                }
            }
        }
        return returnJson;
    }

    /**
     * 供应商创建
     *
     * @param paramsList
     * @return
     */
    public JSONObject CreateSupplier(JSONArray paramsList, String requestid, String src) {
        JSONObject returnJson = new JSONObject();
        // 默认设置为失败
        returnJson.put("code", CODE_FAIL);
        returnJson.put("message", MESSAGE_FAIL);
        Map<String, Object> apilogMap = new HashMap<>();
        apilogMap.put("jkdymc", "WeaGyszrsqlcAction");
        apilogMap.put("lcid", requestid);
        apilogMap.put("cz", src);
        String baseUrl = Util.null2String(getPropValue("u9", "url"));
        String apiUrl = "/U9C/webapi/CustSupplier/CreateSupplier";
        JSONObject resultJson = doApiLog(paramsList, apilogMap, baseUrl + apiUrl);
        writeLog(">>>>>CreateSupplier>>>>>resultJson=" + resultJson);
        if (MESSAGE_SUCCESS.equals(resultJson.getString("message"))) {
            JSONObject dataJson = resultJson.getJSONObject("data");
            if (RES_CODE_ZERO.equals(dataJson.getString("ResCode"))) {
                JSONArray resultData = dataJson.getJSONArray("Data");
                if (!resultData.isEmpty()) {
                    JSONObject firstObject = resultData.getJSONObject(0);
                    String isSucess = firstObject.getString("IsSucess");
                    if (IS_SUCCESS_TRUE.equals(isSucess)) {
                        returnJson.put("code", CODE_SUCCESS);
                        String data = firstObject.getString("ID");
                        returnJson.put("data", data);
                    } else {
                        returnJson.put("message", firstObject.getString("ErrorMsg"));
                    }
                } else {
                    returnJson.put("message", dataJson.getString("ResMsg"));
                }
            }
        }
        return returnJson;
    }

    /**
     * 审批状态回传
     *
     * @param paramsJson
     * @return
     */
    public JSONObject AppovedFKD(JSONObject paramsJson, String requestid, String src) {
        Map<String, Object> apilogMap = new HashMap<>();
        apilogMap.put("jkdymc", "WeaGyszrsqlcAction");
        apilogMap.put("lcid", requestid);
        apilogMap.put("cz", src);
        String baseUrl = Util.null2String(getPropValue("u9", "url"));
        String apiUrl = "/U9C/RestServices/AppovedFKD_SXOA.IPayReqFundProxy.svc/do";
        return doApiLog2(paramsJson, apilogMap, baseUrl + apiUrl);
    }

    /**
     * 插入接口日志
     *
     * @param paramsList
     * @param apilogMap
     * @return
     */
    private JSONObject doApiLog(JSONArray paramsList, Map<String, Object> apilogMap, String url) {
        JSONObject resultJson = sendOKHttpPostRequest(url, paramsList.toJSONString());
        apilogMap.put("jkqqcs", paramsList);
        apilogMap.put("jkxycs", resultJson);
        insertApiLog(apilogMap);
        return resultJson;
    }

    /**
     * 插入接口日志
     *
     * @param params
     * @param apilogMap
     * @return
     */
    private JSONObject doApiLog2(JSONObject params, Map<String, Object> apilogMap, String url) {
        JSONObject resultJson = sendOKHttpPostRequest(url, params.toJSONString());
        apilogMap.put("jkqqcs", params);
        apilogMap.put("jkxycs", resultJson);
        insertApiLog(apilogMap);
        return resultJson;
    }

    /**
     * 获取token
     *
     * @return
     */
    private String getAuthLogin() {
        String token = "";
        String apiUrl = "/U9C/webapi/OAuth2/AuthLogin";
        String baseUrl = Util.null2String(getPropValue("u9", "url"));
        String userCode = Util.null2String(getPropValue("u9", "userCode"));
        String entcode = Util.null2String(getPropValue("u9", "entcode"));
        String orgcode = Util.null2String(getPropValue("u9", "orgcode"));
        String clientId = Util.null2String(getPropValue("u9", "clientId"));
        String clientSecret = Util.null2String(getPropValue("u9", "clientSecret"));
        String url = baseUrl + apiUrl + "?userCode=" + userCode + "&entcode=" + entcode + "&orgcode=" + orgcode + "&clientid=" + clientId + "&clientsecret=" + clientSecret;
        JSONObject resultJson = sendOKHttpGetRequest(url);
        writeLog(">>>>>getAuthLogin>>>>>>resultJson=" + resultJson);
        String message = Util.null2String(resultJson.getString("message"));
        if ("success".equals(message)) {
            JSONObject dataJson = resultJson.getJSONObject("data");
            String ResCode = Util.null2String(dataJson.getString("ResCode"));
            if ("0".equals(ResCode)) {
                token = Util.null2String(dataJson.getString("Data"));
            }
        }
        return token;
    }

    /**
     * get请求
     *
     * @param apiUrl
     * @return
     */
    private JSONObject sendOKHttpGetRequest(String apiUrl) {
        writeLog(">>>>>sendOKHttpGetRequest>>>>>>apiUrl=" + apiUrl);
        JSONObject resultJson = new JSONObject();
        String responseMsg = "";
        try {
            Request request = new Request.Builder()
                    .url(apiUrl)
                    .get()
                    .build();
            Response response = client.newCall(request).execute();
            String result = Util.null2String(response.body().string());
            response.body().close(); // 保证资源被释放
            // 增加对HTTP状态码的检查
            if (!response.isSuccessful()) {
                responseMsg = "response code :" + response.code();
            } else {
                if (!result.isEmpty()) {
                    resultJson.put("data", result);
                    responseMsg = "success";
                } else {
                    responseMsg = "response result is null";
                }
            }
        } catch (Exception e) {
            responseMsg = "response timeout or network error";
            writeLog(">>>>>sendOKHttpGetRequest>>>>>Exception e:", e);
        }

        resultJson.put("message", responseMsg);
        return resultJson;
    }

    /**
     * Post请求
     *
     * @param params
     * @param apiUrl
     * @return
     */
    public JSONObject sendOKHttpPostRequest(String apiUrl, String params) {
        String token = getAuthLogin();
        JSONObject resultJson = new JSONObject();
        String responseMsg = "";
        try {
            RequestBody body = RequestBody.create(mediaType, params);
            Request request = new Request.Builder()
                    .url(apiUrl)
                    .method("POST", body)
                    .addHeader("token", token)
                    .addHeader("Content-Type", "application/json")
                    .build();
            Response response = client.newCall(request).execute();
            String result = Util.null2String(response.body().string());
            response.body().close(); // 保证资源被释放
            // 增加对HTTP状态码的检查
            if (!response.isSuccessful()) {
                responseMsg = "response code :" + response.code();
            } else {
                if (!result.isEmpty()) {
                    resultJson.put("data", result);
                    responseMsg = "success";
                } else {
                    responseMsg = "response result is null";
                }
            }
        } catch (Exception e) {
            responseMsg = "response timeout or network error";
            writeLog(">>>>>sendOKHttpPostRequest>>>>>Exception e:", e);
        }
        resultJson.put("message", responseMsg);
        return resultJson;
    }


    /**
     * 插入接口日志
     *
     * @param dataMap
     */
    private void insertApiLog(Map<String, Object> dataMap) {
        dataMap.put("jkqqdz", getPropValue("u9", "url"));
        dataMap.put("jkdysj", DateUtil.getFullDate());
        dataMap.put("jktgf", "U9");
        insertModelData(dataMap);
    }


    /**
     * 建模权限重构
     *
     * @param userid
     * @param formmodeid
     * @param id
     */
    private void newModeRight(int userid, int formmodeid, int id) {
        ModeRightInfo modeRightInfo = new ModeRightInfo();
        modeRightInfo.setNewRight(true);
        modeRightInfo.editModeDataShare(userid, formmodeid, id);
    }

    /**
     * 将数据插入表单建模
     *
     * @param map
     */
    private void insertModelData(Map<String, Object> map) {
        String tablename = "uf_apilog";
        int userid = 1;
        RecordSet rs = new RecordSet();
        RecordSet rs1 = new RecordSet();
        //查询该模块表名
        try {
            rs.executeQuery("select a.id from modeinfo a left join workflow_bill b on a.formid=b.id where b.tablename='" + tablename + "'");
            rs.next();
            int modeid = Util.getIntValue(rs.getString("id"));
            String uuid = UUID.randomUUID().toString();
            String insSql = "insert into " + tablename
                    + "(modeuuid,modedatacreater,modedatacreatedate,modedatacreatetime,formmodeid)values" +
                    "('" + uuid + "','" + userid + "','" + TimeUtil.getCurrentDateString() + "','" + TimeUtil.getOnlyCurrentTimeString() + "','" + modeid + "')";
            rs.executeUpdate(insSql);
            rs1.executeQuery("select id from " + tablename + " where modeuuid='" + uuid + "'");
            rs1.next();
            int dataid = Util.getIntValue(rs1.getString("id"));
            if (dataid > 0) {
                //遍历数据 进行update
                String updatesql = "update " + tablename + " set ";
                Set<String> keySet = map.keySet();
                for (String key : keySet) {
                    String value = Util.null2String(map.get(key)).replace("'", "").replace("-", "").replace(" ", "");
                    updatesql += key + "='" + value + "',";
                }
                if (updatesql.endsWith(",")) {
                    updatesql = updatesql.substring(0, updatesql.length() - 1);
                    updatesql += " where id=" + dataid;
                    if (!rs.executeUpdate(updatesql)) {
                        rs1.executeUpdate("delete from " + tablename + " where id=?", dataid);
                    }
                }
                //进行权限重构
                newModeRight(userid, modeid, dataid);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}
